package com.common.config.interceptor;

/**
 * ClassName: LoginInterceptor
 * Package: com.sixkey.interceptorconfig
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2023/11/1 - 21:50
 * @Version: v1.0
 */

import cn.dev33.satoken.stp.StpUtil;
import com.common.exception.SystemException;
import com.common.response.ResponseCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;
import java.util.regex.Pattern;


/**
 * 自定义配置请求拦截器，所有的请求都会先通过这里
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 白名单路径集合
     */
    private List<String> whitelistedPaths;

    /**
     * 通过构造函数注入白名单路径集合
     * @param whitelistedPaths
     */
    public LoginInterceptor(List<String> whitelistedPaths) {
        this.whitelistedPaths = whitelistedPaths;
    }

    /**
     * 请求转发之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestPath = request.getRequestURI();

        // 判断当前路径是否在白名单中
        if (isWhitelisted(requestPath)) {
            // 如果是白名单路径，则直接放行
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("authorization");
        if (StringUtils.isEmpty(token)) {
            // 如果token为空，则抛出异常
            throw new SystemException(ResponseCodeEnum.NO_PERMISSION);
        }

        // 先检查是否已被冻结
        StpUtil.checkActiveTimeout();

        // 为指定Token续签
        StpUtil.stpLogic.updateLastActiveToNow(token);

        // 如果一切正常，则放行请求
        return true;
    }

    /**
     * 判断路径是否在白名单中的方法
     * @param requestPath
     * @return
     */
    private boolean isWhitelisted(String requestPath) {
        return whitelistedPaths.stream()
                .anyMatch(pattern -> Pattern.matches(pattern.replace("**", ".*"), requestPath));
    }
}
